<?php

namespace App\Recharge\Api;

use App\Recharge\Bean\ApiNotifyDataBean;
use App\Recharge\Bean\BasicInformation;
use App\Traits\Create;
use GuzzleHttp\Promise\PromiseInterface;
use App\Recharge\Interfaces\ApiInterface;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Contracts\Routing\ResponseFactory;
use Illuminate\Http\Client\PendingRequest;
use App\Models\Admin\InterfaceConfiguration;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Response;

abstract class AbstractApi implements ApiInterface
{
    use Create;

    /**
     * @param PendingRequest $http
     * @param int $timeout
     * @return PendingRequest
     */
    protected function httpClient(PendingRequest $http, int $timeout = 60): PendingRequest
    {
        return $http->async()->timeout($timeout)->withoutVerifying();
    }

    /**
     * @param string $order_no
     * @param mixed $state
     * @return ApiNotifyDataBean
     */
    protected function apiNotifyData(string $order_no, mixed $state): ApiNotifyDataBean
    {
        $bean = new ApiNotifyDataBean();
        return $bean->setOrderNo($order_no)->setState($state);
    }

    /**
     * @param PendingRequest $http
     * @param InterfaceConfiguration $config
     * @param BasicInformation $bean
     * @return PromiseInterface
     */
    public function recharge(PendingRequest $http, InterfaceConfiguration $config, BasicInformation $bean): PromiseInterface
    {
        $client = match ($config->api_data_format) {
            'json'      => $this->httpClient($http)->asJson(),
            'multipart' => $this->httpClient($http)->asMultipart(),
            default     => $this->httpClient($http)->asForm(),
        };
        return match ($config->method) {
            'get', 'GET' => $client->get($config->recharge_url, $this->rechargeData($bean)),
            default => $client->post($config->recharge_url, $this->rechargeData($bean)),
        };
    }

    /**
     * @return mixed
     */
    public function apiNotifySuccess(): mixed
    {
        return response('ok');
    }
}
